/*
 * @Author: 徐建辰
 * @LastEditors: 徐建辰
 * @Description: http请求
 * @params {options} 请求配置项
 * @params {callback} 请求完成后的回调
 */
import {httpUrl} from '@/utils/constant'
import {getToken} from '@/utils/local'
import {isObject} from '@/utils/type'

export default function request(options, callback) {
	return new Promise((resolve, reject) => {
		uni.getNetworkType({
			success({networkType}) {
				if (networkType === 'none') {
					uni.showToast({
						icon: 'error',
						title: '无网络！'
					})
					return
				}
				// 此处应该用后端返回的token  const token = getToken()
				const token = 'JSESSIONID=d08e3e0e-1341-4625-b9e4-dd318a52e1a0'
				if (!token) {
					uni.showModal({
						showCancel: false,
						content: '未登录'
					})
					return
				}
				
				const {
					url,
					method = 'GET', 
					data = {}, 
					header = {},
					mask = false,           // 是否开启loading mask
					loading = true,         // 是否loading
					title = '加载中...',     // loading文字
					hideLoadingTime = 500   // 多少毫秒隐藏loading
				} = options
				const tHeader = {'Authorization': token, ...header}
				
				loading && uni.showLoading({title, mask})
				uni.request({
					url,
					method,
					data,
					header: tHeader,
					//#ifndef H5
					withCredentials: true,
					//#endif
					success(res) {
						// 针对错误码进行处理
						const {statusCode, data = {}} = res
						const errCodes = [400, 401, 403, 404, 500, 502, 503, 504]
						if (errCodes.includes(statusCode)) {
							const errMsg = {
								400: '请求错误',
								401: '登录状态失效，请重新登录',
								403: '拒绝访问',
								404: '请求地址不存在',
								500: '服务器繁忙',
								502: '网关错误',
								503: '服务不可用，服务器暂时过载或维护',
								504: '网关超时'
							}
							uni.showToast({
								title: data.msg || errMsg[statusCode],
								icon: 'none'
							})
							return Promise.reject(res)
						}
						
						resolve(res.data)
					},
					fail(err) {
						uni.showToast({
							title: '请求数据失败',
							icon: 'error'
						})
						reject(err)
					},
					complete() {
						setTimeout(() => wx.hideLoading(), hideLoadingTime)
						callback && callback()
					}
				})
			},
			fail(err) {
				uni.showToast({
					title: 'getNetworkType fail'
				})
				console.log(err)
			}
		})
	})
}